#pragma once

#include<iostream>
#include<string>
#include<ctime>
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<stdarg.h>

const std::string filename = "./log/tcpserver.log";

enum
{
    Debug = 0,
    Info,
    Warning,
    Error,
    Fatal,
    Uknown
};

static std::string getLevelString(int level)
{
    switch (level)
    {
    case Debug:
        return "Debug";
    case Info:
        return "Info";
    case Warning:
        return "Warning";
    case Error:
        return "Error";
    case Fatal:
        return "Fatal";
    default:
        return "Uknown";
    }
}

static std::string gettime()
{
    time_t cur=time(nullptr);
    struct tm* tmp=localtime(&cur);
    char buffer[128];
    snprintf(buffer,sizeof(buffer),"%d-%d-%d %d:%d:%d",tmp->tm_year+1,tmp->tm_mon+1,tmp->tm_mday+1,
                                    tmp->tm_hour,tmp->tm_min,tmp->tm_sec);
    return buffer;
}

//日志组成：日志等级 时间 PID 消息内容

//日志等级 格式控制 可变参数
void logMessage(int level,const char*format,...)
{
    char logLeft[1024];
    std::string level_string=getLevelString(level);
    std::string time_string=gettime();
    std::string pid_string=std::to_string(getpid());

    snprintf(logLeft,sizeof(logLeft),"[%s] [%s] [%s] ",level_string.c_str(),time_string.c_str(),pid_string.c_str());

    char logRight[1024];
    va_list p;//类似指针
    va_start(p,format);//将p定位到可变参数首地址
    vsnprintf(logRight,sizeof(logRight),format,p);//按format格式将可变参数写入logRight

    va_end(p);//将va_list清理

    //打印日志信息
    printf("%s%s\n",logLeft,logRight);
    //std::cout<<logLeft<<logRight<<std::endl;

    // // 保存到文件中
    // FILE *fp = fopen(filename.c_str(), "a");
    // if(fp == nullptr)return;
    // fprintf(fp,"%s%s\n", logLeft, logRight);
    // fflush(fp); //可写也可以不写
    // fclose(fp);
}